package com.itheima.config;

import com.itheima.excecption.CustomException;
import com.itheima.excecption.NotLocalException;
import com.itheima.tool.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice(annotations = {RestController.class, Controller.class})

public class GlobalExceptionHandle {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R SQLIntegrityConstraintViolationExceptionHande(SQLIntegrityConstraintViolationException e){
        if(e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");


    }




    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        return R.error(ex.getMessage());
    }


    @ExceptionHandler(NotLocalException.class)
    public R<String> NotLocalException(NotLocalException e){
        return R.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R AllExceptionHanlder(Exception e){
        e.printStackTrace();
        String message = "未知错误,请联系业务员";
        return R.error(message);
    }



}
